<template>
    <el-dialog
            :before-close="closeDialog"
            :title="isEdit?'修改订餐':'新增订餐'"
            :visible.sync="localFormVisible"
            top="15px"
            width="60%"
            style="height: 1500px"
            :close-on-click-modal="false"
    >
        <div class="form-content">
            <el-row >
                <el-col :offset="19" :span="5" >
                    <el-button-group>
                        <el-button icon="el-icon-plus" type="primary" @click="saveOrder">保存</el-button>
                        <el-button icon="el-icon-edit" type="primary" @click="submitOrder">提交</el-button>
                    </el-button-group>
                </el-col>
            </el-row>
            <el-form ref="orderForm" :model="orderRequest">
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="订餐编号" prop="orderID">
                            <el-input :value="orderRequest.order.orderId" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :offset="2" :span="11" prop="empId">
                        <el-form-item label="发起人编号">
                            <el-input :value="orderRequest.order.empId" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="发起人姓名">
                            <el-input :value="this.$store.state.user.empName" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :offset="2" :span="11">
                        <el-form-item label="发起日期">
                            <el-date-picker
                                    v-model="orderRequest.order.orderdate" disabled style="width: 100%;" type="date"
                                    value-format="yyyy-MM-dd"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="总金额">
                            <el-input :value="orderRequest.order.totalprice" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :offset="2" :span="11">
                        <el-form-item label="订餐备注">
                            <el-input
                                    v-model="orderRequest.order.orderNote" :rows="4" placeholder="请输入订餐备注"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="选择员工" prop="empList">
                    <div @click="openEmp">
                        <el-input
                                :value="empNames.join(',')" disabled placeholder="请选择订餐员工"
                                prefix-icon="el-icon-s-custom"
                        ></el-input>
                        <!-- 透明按钮或div，用于触发点击事件 -->
                        <div class="transparent-button"></div>
                    </div>
                </el-form-item>
                <span>当前订餐人数为{{ totalEmp }}人</span>
            </el-form>
            <el-button @click="openMeal">选择餐品
            </el-button>
            <el-button
                    :disabled="multipleSelection.length === 0"
                    type="danger"
                    @click="removeSelectedMeals"
            >移除餐品
            </el-button>
            <p>当前选择餐品为{{ totalMeal }}份,总金额为{{ totalPrice }}元,</p>
            <el-table
                    :data="orderRequest.mealList"
                    :height="300"
                    border
                    stripe
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column prop="mealId" type="selection"></el-table-column>
                <el-table-column label="序号" type="index" width="60"></el-table-column>
                <el-table-column label="餐品名称" prop="mealName" width="180"></el-table-column>
                <el-table-column :formatter="formatPrice" label="餐品单价" prop="price" width="180"></el-table-column>
                <el-table-column label="图片" prop="imageUrl" width="150">
                    <template v-slot="scope">
                        <img
                                v-if="scope.row.imageUrl"
                                :src="require('@/assets/images/' + scope.row.imageUrl)"
                                alt="餐品图片"
                                style="width: 70px; height: 70px;"
                        >
                    </template>
                </el-table-column>
                <!-- 设置数量上限为选中员工数量 -->
                <el-table-column label="数量" width="185">
                    <template v-slot="scope">
                        <el-input-number
                                v-model="scope.row.count"
                                :max="getMaxCount(scope.row.count)"
                                :min="1"
                                @change="handleCountChange"
                        ></el-input-number>
                    </template>
                </el-table-column>
            </el-table>
            <p v-if="isMealCountExceeded" style="color: red;">警告：选择的餐品总数不能超过订餐人数！</p>
            <OrderEmp
                    :emp-list="orderRequest.empList"
                    :formVisible.sync="empFormVisible"
                    @submitForm="setEmp"
            ></OrderEmp>

            <!-- 传递选中员工数量作为最大餐品数量 -->
            <OrderMeal
                    :form-visible.sync="mealFormVisible"
                    :max-meal-count="totalEmp"
                    @submitForm="setMeal"
            ></OrderMeal>
        </div>
    </el-dialog>

</template>

<script>
import OrderEmp from "@/views/order/OrderEmp.vue";
import OrderMeal from "@/views/order/OrderMeal.vue";

export default {
    name: "OrderView",
    components: {OrderEmp, OrderMeal},
    data() {
        return {
            localFormVisible: this.orderFormVisible,
            empNames: '',
            empIds: [],
            multipleSelection: [],
            mealFormVisible: false,
            empFormVisible: false,
            isMealCountExceeded: false, // 标记是否超出订餐人数
        };
    },
    methods: {
        openEmp() {
            this.empFormVisible = true;
        },
        openMeal() {
            this.mealFormVisible = true;
        },
        //拿到选中的员工,并且取出选中的员工名字,将名字显示在input框中
        setEmp(selectedItems) {
            this.empNames = selectedItems.map(item => item.label); // 更新显示的员工姓名
            this.empIds = selectedItems.map(item => item.key); // 更新员工ID
            this.orderRequest.empList = selectedItems.map(item => ({
                empId: item.key,
                empName: item.label
            }));
            this.empFormVisible = false;
        },
        //拿到选中餐品并显示在选择餐品的表格中
        setMeal(selectedMeals) {
            this.orderRequest.mealList = selectedMeals.map(item => ({
                ...item,//将选中的餐品的对象的属性展开并复制到新的对象中
                count: 1 // 默认数量为1
            }));
            this.mealFormVisible = false; // 关闭弹框
        },
        formatPrice(row, column, cellValue, index) {
            // 使用 toFixed 方法来格式化小数，保留两位小数
            // toFixed 返回的是一个字符串
            return Number(cellValue).toFixed(2);
        },
        handleCountChange() {
            this.validateMealCount(); // 选择餐品数量改变时验证
        },
        validateMealCount() {
            this.isMealCountExceeded = this.totalMeal > this.totalEmp;
        },
        getMaxCount(currentCount) {
            // 剩余的可分配餐品数量：当前员工总数 - 当前所选所有餐品总数 + 当前餐品已经选择份数
            const remainingCount = this.totalEmp - this.totalMeal + currentCount;
            return remainingCount >= 0 ? remainingCount : 0;
        },

        // 处理表格中复选框选中项
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 移除选中餐品
        removeSelectedMeals() {
            this.orderRequest.mealList = this.orderRequest.mealList.filter(item => !this.multipleSelection.includes(item));
            this.multipleSelection = []; // 清空选中项
        },
        saveOrder() {
            // 校验备注是否填写
            if (!this.orderRequest.order.orderNote) {
                this.$message.warning('请填写订餐备注');
                return;
            }
            // 校验是否选择员工
            if (this.totalEmp === 0) {
                this.$message.warning('请选择订餐员工');
                return;
            }
            // 校验餐品数量是否正确
            if (this.totalMeal !== this.totalEmp) {
                this.$message.warning(`请检查餐品和员工数量是否一致`);
                return;
            }
            this.orderRequest.submitFlag = false;
            this.saveForm();
        },
        submitOrder() {
            // 校验备注是否填写
            if (!this.orderRequest.order.orderNote) {
                this.$message.warning('请填写订餐备注');
                return;
            }
            // 校验是否选择员工
            if (this.totalEmp === 0) {
                this.$message.warning('请选择订餐员工');
                return;
            }
            // 校验餐品数量是否正确
            if (this.totalMeal !== this.totalEmp) {
                this.$message.warning(`请检查餐品和员工数量是否一致`);
                return;
            }
            // 提交订单
            this.orderRequest.submitFlag = true;
            this.saveForm();
        },
        //向后端提交
        saveForm() {
            const self = this;
            self.orderRequest.order.empId = this.$store.state.user.empId // 提交人
            self.orderRequest.mealList = Array.isArray(this.orderRequest.mealList) ?
                this.orderRequest.mealList.map(item => ({
                    mealId: item.mealId,
                    mealCount: item.count || 0 // 设置默认值为 0，如果未定义
                })) : [];
            this.$http.post("creatOrEditOrder", self.orderRequest).then(res => {
                if (res.data === 'success') {
                    this.$message({
                        type: 'success',
                        message: '订餐上传成功'
                    })
                } else {
                    this.$message.error("订餐上传失败")
                }
                this.closeDialog()
                this.$emit("orderList")
            }).catch((e) => {
                this.$message.error("保存失败,请...")
                this.closeDialog()
                this.$emit("orderList")
            })
        },
        //计算餐品总价格
        calculateTotalPrice() {
            return this.orderRequest.mealList.reduce((sum, item) => sum + (item.price * item.count), 0).toFixed(2);
        },
        closeDialog() {
            this.localFormVisible = false;
            //通知父组件修改formVisible的值为false
            this.$emit('update:orderFormVisible', false)
        },

    },
    props: {
        orderFormVisible: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false
        },
        orderRequest: {
            type: Object,
        }
    },
    computed: {
        totalEmp() {
            return this.empNames.length;
        },
        totalMeal() {
            return this.orderRequest.mealList.reduce((sum, item) => sum + item.count, 0);
        },
        totalPrice() {
            return this.calculateTotalPrice();
        },

    },
    watch: {
        orderFormVisible(newVal) {
            this.localFormVisible = newVal; // 当 `prop` 改变时，更新本地变量
        },
        totalPrice(newPrice) {
            this.orderRequest.order.totalprice = newPrice; //当totalPrice变化后,更新表单中的总价格
        },
        // 当 orderRequest.empList 改变时，更新 empNames,将订餐员工的姓名显示在输入框中
        'orderRequest.empList': {
            handler(newEmpList) {
                this.empNames = newEmpList.map(emp => emp.empName);
            },
            immediate: true, // 立即执行，确保首次加载时也会触发
            deep: true // 深度监听，处理数组对象的变化
        },
    },
    created() {
    }
}
</script>

<style scoped>

.transparent-button {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1; /* 确保覆盖在 input 上 */
    cursor: pointer; /* 显示鼠标为指针样式 */
    background-color: transparent; /* 透明背景 */
    border: none; /* 无边框 */
    outline: none; /* 去除焦点轮廓 */
}

.form-content {
    height: 600px;
    overflow: auto;
}

</style>
